package model

import (
	"encoding/json"
	"fmt"
	"github.com/garyburd/redigo/redis"
	"go_code/chatroom/common/message"
)

//在服务器启动后，初始化userDao实例
var (
	MyUserDao *UserDao
)

type UserDao struct {
	pool *redis.Pool
}

//使用工厂模式，创建一个UserDao实例
func NewUserDao(pool *redis.Pool)(userDao *UserDao)  {
	userDao = &UserDao{
		pool: pool,
	}
	return
}

//根据用户id返回一个user实例+err
func (this *UserDao)getUserById(conn redis.Conn, id int)(user *User, err error)  {
	//通过给定id，去redis查询用户
	res, err := redis.String(conn.Do("HGet", "users", id))
	if err != nil {
		if err != redis.ErrNil {	//redis中没有找到对应的id
			err = ERROR_USER_NOTEXISTS
		}
		return
	}
	user = &User{}
	 //需要把res反序列化User实例
	err = json.Unmarshal([]byte(res), user)
	if err != nil {
		fmt.Println("json.Unmarshal err=", err)
		return
	}
	return
}

//完成登陆的校验 Login
func (this *UserDao) Login(userId int, userPwd string) (user *User, err error) {
	conn := this.pool.Get()
	defer conn.Close()
	user, err = this.getUserById(conn, userId)
	if err != nil {
		return
	}

	if user.UserPwd != userPwd {
		err = ERROT_USER_PWD
		return
	}
	return
}

//完成注册的校验 Register
func (this *UserDao) Register(user *message.User) (err error) {
	conn := this.pool.Get()
	defer conn.Close()
	_, err = this.getUserById(conn, user.UserId)
	if err == nil {
		err = ERROT_USER_EXISTS
		return
	}

	//id还没有注册过
	data, err := json.Marshal(user)
	if err != nil {
		return
	}

	//入库
	_, err = conn.Do("HSet", "user", user.UserId, string(data))
	if err != nil {
		fmt.Println("保存注册用户错误 err=", err)
		return
	}

	return
}

